﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkitMvvmDemo.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommunityToolkitMvvmDemo.ViewModels
{
    public partial class StudentListViewModel : ObservableRecipient, IRecipient<ValueChangedMessage<Student>>
    {

        [ObservableProperty]   // 会生成 AllowAddNew ， 会自动调用 OnAllowAddNewChanged(value); 
        private bool allowAddNew;

        partial void OnAllowAddNewChanged(bool value) // 重写 OnAllowAddNewChanged 方法，分布方法
        {
            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<bool>(value));
        }


        public ObservableCollection<Student> Students { get; } = new();
        public int StudentCount => Students?.Count ?? 0;

        public StudentListViewModel()
        {
            //zcx  CollectionChanged  集合数据变化事件
            // OnPropertyChanged  去引发一个CommunityToolkit.Mvvm.ComponentModel.ObservableObject.PropertyChanged事件
            Students.CollectionChanged += (_, _) => OnPropertyChanged(nameof(StudentCount));

        }

        // 收到学生消息后
        public void Receive(ValueChangedMessage<Student> message)
        {
            Students.Add(message.Value);
        }
    }
}
